package com.yx.backstage.config.global;

import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author YangXiong
 */
@ControllerAdvice
@Api(tags = "全局异常处理")
public class MyGlobalHandler {
    @Value("${spring.http.multipart.max-file-size}")
    private String fileSize;
    private static final Logger logger = LoggerFactory.getLogger(MyGlobalHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public CommonResult<String> bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return CommonResult.fail(e.getErrorMsg());
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public CommonResult<String> exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("发生空指针异常！原因是:", e);
        return CommonResult.fail("系统异常");
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResult<String> exceptionHandler(Exception e) {
        logger.error("未知异常！原因是:", e);
        return CommonResult.fail(e.getMessage());
    }

    @ExceptionHandler(value = MultipartException.class)
    @ResponseBody
    public CommonResult<String> fileUpException() {
        return CommonResult.fail("文件大小超过了" + fileSize);
    }
}

